const model = require('../../public/model/env.js');

const url = model.api_pro_url(); // 线上环境
const key = model.key();
const appid = model.appid();
const byteid = model.byteid();
const serialNumber = model.generateSerialNumbe();
// console.log(serialNumber);
const background = tt.getStorageSync('background');

// const user_name = tt.getStorageSync('userInfo');//获取用户信息
// let user_names = user_name.nickName;
// let user_icon_url = user_name.avatarUrl;
// const short_user_name = user_name.slice(0, 5)+'...';
// console.log(user_name);

Page({
  data: {
    imId: byteid,
    U_Id: null,
    user_icon: '',
    // user_icon: user_icon,
    user_name: '',
    className: 'containerdark',
    user_desc: '的个人道场',
    button_text: '登入',
    order_num: 0,
    quan_num: 0,
    jifen_num: 0,
    button_text_type: 'getUserInfo',
    login: tt.getStorageSync('userInfo') === '' ? 'login' : '',
    title: '个人中心',
    serialNumbers: serialNumber,
  },
  onPullDownRefresh: function () {
    this.data.serialNumbers = model.generateSerialNumbe();
    this.setData({
      serialNumbers: this.data.serialNumbers + '1',
    });
    console.log(this.data.serialNumbers);
    // 更新页面数据
    this.fetchData();
  },
 fetchData: function () {
  var that = this;
    // 模拟请求数据
    setTimeout(() => {
        // 积分券数量返回
    const requestUrlquan = `${url}/index.php/api/points_cx.php`;
    const quans = {
      url: requestUrlquan,
      data: {
        // appid: appid,
        key: key,
        user_id: that.data.U_Id,
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(quans);
    tt.request({
      ...quans,
      success: (res) => {
        const data = res.data;
        // console.log(data.data.points);
        that.setData({
          jifen_num: data.data.points,
          quan_num: data.data.ticket
        });
      },
      fail: (err) => {
        console.log(err);
      }
    });




    // 订单返回
    const requestUrlorder = `${url}/index.php/api/order_list.php`;
    const orders = {
      url: requestUrlorder,
      data: {
        appid: appid,
        key: key,
        user_id: that.data.U_Id,
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(orders);
    tt.request({
      ...orders,
      success: (res) => {
        const data = res.data;
        // console.log(data);
        if (data.code == 200) {
          // console.log('数组包含的元素数量:', data.data.length);
          that.setData({
            order_num: data.data.length
          });
        }
      },
      fail: (err) => {
        console.log(err);
      }
    });

      // 停止下拉刷新
      tt.stopPullDownRefresh();
    }, 1500);
  },
  //分享
  async onShareAppMessage() {
    const self = this;

    return {
      title: `周易占卜第${self.data.U_Id}封邀请函`,
      desc: "邀请你一起参与周易占卜，一起寻找命运的奥秘",
      path: `/pages/index/index?fromcode=${self.data.U_Id}`,
      // console.log(this.data.U_Id),
      // templateId: "r30qx0gd326b69b383",
      success() {
        // 积分增加
        // console.log(path);
        console.log(self.data.U_Id);
        const requestUrl = `${url}/index.php/api/points_add.php`;

        const options = {
          url: requestUrl,
          data: {

            user_id: self.data.U_Id,
            ticket_title: 901,
            Invitee_open_id: self.data.serialNumbers + self.data.U_Id,
            key: key
          },
          method: 'GET',
          header: {
            'content-type': 'application/json'
          },
          dataType: 'json',
        };
        console.log(options);
        tt.request({
          ...options,
          success: (res) => {
            const data = res.data;
            console.log(data);
            if (data.code == 200) {
              self.setData({
                jifen_num: self.data.jifen_num + 10,
              });
              tt.showToast({ title: '积分增加', icon: 'none', duration: 2000 });
            }
            if (data.code == 400) {
              tt.showToast({ title: data.message, icon: 'fail', duration: 2000 });
            }
          },
          fail: (err) => {
          }
        })
        // 积分增加结束

      },
      fail() {
        console.log("转发发布器调起失败");
      },
    };
  },
  // 分享结束
  imCallback(e) {
    console.log("跳转IM客服成功", e.detail);
  },
  onimError(e) {
    console.log("拉起IM客服失败", e.detail);
  },
  getUserInfo(res) {//获取用户信息

    const { userInfo, errMsg, rawData } = res.detail;
    this.setData({
      userInfo,
      errMsg,
      rawData
    });
    // console.log("获取用户信息成功", userInfo);
    if (userInfo) {
      this.setData({
        user_name: userInfo.nickName.slice(0, 6) + '...',
        user_icon: userInfo.avatarUrl,
        button_text: '你好',
        button_text_type: 'logout',


      });
      tt.setStorageSync('userInfo', userInfo.nickName);
      tt.setStorageSync('user_icon', userInfo.avatarUrl);
      tt.showToast({
        title: userInfo.nickName,
      });
    }
    // 积分券数量返回
    const requestUrlquan = `${url}/index.php/api/points_cx.php`;
    const quans = {
      url: requestUrlquan,
      data: {
        // appid: appid,
        key: key,
        user_id: this.data.U_Id,
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(quans);
    tt.request({
      ...quans,
      success: (res) => {
        const data = res.data;
        console.log(data.data.points);
        this.setData({
          jifen_num: data.data.points,
          quan_num: data.data.ticket
        });
      },
      fail: (err) => {
        console.log(err);
      }
    });




    // 订单返回
    const requestUrlorder = `${url}/index.php/api/order_list.php`;
    const orders = {
      url: requestUrlorder,
      data: {
        appid: appid,
        key: key,
        user_id: this.data.U_Id,
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(orders);
    tt.request({
      ...orders,
      success: (res) => {
        const data = res.data;
        // console.log(data);
        if (data.code == 200) {
          // console.log('数组包含的元素数量:', data.data.length);
          this.setData({
            order_num: data.data.length
          });
        }
      },
      fail: (err) => {
        console.log(err);
      }
    });

    //             // 订单返回结束
    const requestUrl = `${url}/index.php/api/sev_user.php`;
    const options = {
      url: requestUrl,
      data: {
        appid: appid,
        user_id: this.data.U_Id,
        key: key,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,

      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(options);
    tt.request({
      ...options,
      success: (res) => {
        const data = res.data;
        // console.log(data);
        if (data.code == 206) {
          console.log('头像上传成功');
        } else {
          console.log('头像上传失败');
        }
      },
      fail: (err) => {
        console.log(err);
      }
    })


  },//获取用户信息结束
  onLoad: function () {


    // 页面加载,标题设置
    tt.setNavigationBarTitle({
      title: this.data.title,
    });
    tt.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000000',
    });
    // 页面加载,标题设置结束
    const that = this; // 保存 this 指针
    // 检查是否存在 userid
    const userid = tt.getStorageSync('userid');
    console.log('userid:'+userid);
    if (userid) {
      console.log('userid 已存在，不触发登录');
      that.setData({
        U_Id: userid,
        // 如果需要，可以在这里设置其他数据
      });
    } else {
      console.log('userid 不存在，触发登录');
      // 调用登录
      tt.login({

        force: true,
        success(res) {
          // console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
          const requestUrl = `${url}/index.php/api/login`;
          const options = {
            url: requestUrl,
            data: {
              appid: appid,
              key: key,
              code: res.code,
              anonymous_code: res.anonymousCode
            },
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            dataType: 'json',
          };
          // console.log(options);
          tt.request({
            ...options,
            success: (res) => {
              const data = res.data;
              if (data.code == 206) {
                console.log('已注册');
                tt.setStorageSync('userid', data.id);
                tt.setStorageSync('usercookie', data.unionid);
                console.log(data.id);



                // 将 data.id 的值赋给 data 中的 U_Id
                that.setData({
                  U_Id: data.id,
                  // order_num: data.order_num
                });
              }
            },
            fail: (err) => {
              console.log(err);
            }
          });
        },
        fail(res) {
          console.log(`login 调用失败`);
        },
      });
    }


    // 背景色切换
    if (background == 'naight') {
      this.setData({
        className: 'containerdark'
      });
    } else {
      this.setData({
        className: 'containerlight'
      });
    }
    // 背景色切换结束



  },
  go_order: function () {
    tt.navigateTo({
      url: '../mylist/mylist',
    });
  },
  go_jifen: function () {
    tt.navigateTo({
      url: '../myjifen/myjifen',
    });
  },
  go_ticket: function () {
    tt.navigateTo({
      url: '../mytickt/mytickt',
    });
  },
  go_bazi: function () {
    tt.navigateTo({
      url: '../mybazi/mybazi',
    });
  },

});
